import { Injectable } from '@angular/core';
import { Headers, Http, Response, URLSearchParams } from '@angular/http';
import { BASEURL } from "shared";

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class TreemapService {
  constructor(private http: Http) { }

  private extractData(res: Response) {
    let body = res.json();
    return body;
  }

  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.errCode || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    // return Observable.throw(errMsg);
    return Observable.empty();
  }

  getBlock(type): Observable<any> {
    let url = `${BASEURL}/stock/quotes/block`
    let params = new URLSearchParams()
    params.set('type', type)
    return this.http.get(url, { search: params })
      .map(this.extractData)
      .catch(this.handleError)
  }

  getBlock2symbols(symbol): Observable<any> {
    let url = `${BASEURL}/stock/block2symbols/${symbol}`
    return this.http.get(url)
      .map(this.extractData)
      .catch(this.handleError)
  }

  getTreeMap(): Observable<any> {
    let url = `${BASEURL}/stock/summaries/treemap`
    return this.http.get(url)
      .map(this.extractData)
      .catch(this.handleError)
  }
}